package com.example.zzx.dovebook.bookshare.booksharehome;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.example.baselibrary.commonutil.FormatUtil;
import com.example.baselibrary.commonutil.Logger;
import com.example.baselibrary.commonutil.PictureUriUtil;
import com.example.baselibrary.image.GlideManager;
import com.example.baselibrary.image.MatisseManager;
import com.example.baselibrary.permission.PermissionCheck;
import com.example.zzx.dovebook.R;
import com.example.zzx.dovebook.location.LocationActivity;
import com.example.zzx.dovebook.user.UserManager;
import com.example.zzx.dovebook.utils.LocationUtil;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import java.io.File;
import java.io.IOException;
import java.util.List;

import static android.app.Activity.RESULT_OK;

public class UploadDialog extends BottomSheetDialog {

    private static final String TAG = "UploadDialog";
    private String CACHE_DIR_NAME = "";

    private BookShareHomeActivity mActivity;

    private RelativeLayout mRootView;

    @BindView(R.id.upload_dialog_cover)
    ImageView coverImage;
    @BindView(R.id.upload_dialog_book_name_edit)
    EditText bookNameEdit;
    @BindView(R.id.upload_dialog_book_author_edit)
    EditText bookAuthorEdit;
    @BindView(R.id.upload_dialog_book_isbn_edit)
    EditText bookIsbnEdit;
    @BindView(R.id.upload_dialog_description_edit)
    EditText descriptionEdit;
    @BindView(R.id.upload_dialog_location_btn)
    Button locationBtn;
    @BindView(R.id.upload_dialog_upload_btn)
    Button uploadBtn;

    static final int PICTURE_WAY_TAKE = 0;
    static final int PICTURE_WAY_ALBUM = 1;

    static final int REQUEST_CODE_LOCATION = 0xEF;

    private String mCoverPath = "";
    private Uri mCoverCameraUri;
    private File tempCoverFile;
    private static final String TEMP_COVER_DIR_NAME = "Book/TempCover";
    private static final String TEMP_COVER_FILE_NAME = "temp_cover_image";
    private static final String COVER_FILE_PROVIDER_AUTHORITIES = "com.example.zzx.dovebook.file.provider";

    private PoiItem location;
    private LatLonPoint currentLatLon;
    private String currentLocationInfo;
    private int mQmuiDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    private boolean hasLocationInfo = false;

    public UploadDialog(@NonNull Context context) {
        super(context);
        if (!(context instanceof BookShareHomeActivity)) {
            throw new IllegalArgumentException("context is not instanceof BookShareHomeActivity");
        }
        mActivity = (BookShareHomeActivity) context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRootView = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.dialog_book_share_upload, null);
        setContentView(mRootView);
        ButterKnife.bind(this, mRootView);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        getDelegate().findViewById(R.id.design_bottom_sheet)
                .setBackgroundResource(R.drawable.top_corner);

        setupCoverImage();

        setupUploadBtn();

        setupLocationBtn();

        if (!hasLocationInfo) {
            locationBtn.post(() -> getLocationInfo());
        }
    }

    private void getLocationInfo() {
        LocationUtil.INSTANCE.locationAndGeocode(getContext(), new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int resultCode) {
                if (resultCode != 1000) {
                    Logger.e(TAG, "onRegeocodeSearched -> 获取地址信息失败!");
                    return;
                }
                RegeocodeAddress address = regeocodeResult.getRegeocodeAddress();
                if (address.getPois().size() == 0) {
                    double latitude = UserManager.getInstance(getContext()).getLatitude();
                    double longitude = UserManager.getInstance(getContext()).getLongitude();
                    currentLatLon = new LatLonPoint(latitude, longitude);
                } else {
                    PoiItem poiItem = address.getPois().get(0);
                    currentLatLon = poiItem.getLatLonPoint();
                    currentLocationInfo = address.getCity() + address.getDistrict() + poiItem.getTitle();
                    locationBtn.setText("#" + currentLocationInfo + "#");
                    hasLocationInfo = true;
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        }, true);
    }

    private void setupLocationBtn() {
        locationBtn.setOnClickListener((view) -> {
            Intent intent = new Intent(mActivity, LocationActivity.class);
            if (currentLatLon != null) {
                intent.putExtra("lat_lon_point", currentLatLon);
            }
            if (!TextUtils.isEmpty(currentLocationInfo)) {
                intent.putExtra("location_keyword", currentLocationInfo);
            }
            mActivity.startActivityForResult(intent, REQUEST_CODE_LOCATION);
        });
    }

    private void setupUploadBtn() {
        uploadBtn.setOnClickListener((v) -> {
            String bookName = bookNameEdit.getEditableText().toString();
            String bookAuthor = bookAuthorEdit.getEditableText().toString();
            String bookIsbn = bookIsbnEdit.getEditableText().toString();
            String description = descriptionEdit.getEditableText().toString();
            mActivity.uploadBookShare(mCoverPath, bookName, bookAuthor, bookIsbn, description, currentLatLon);
        });
    }

    private void setupCoverImage() {
        coverImage.setOnClickListener((v) -> {
            String[] pictureWays = getContext().getResources().getStringArray(R.array.picture_type);
            new QMUIDialog.MenuDialogBuilder(getContext())
                    .addItems(pictureWays, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case PICTURE_WAY_TAKE:
                                    getPicFromCamera();
                                    break;
                                case PICTURE_WAY_ALBUM:
                                    openAlbum();
                                    break;
                            }
                            dialog.dismiss();
                        }
                    }).create(mQmuiDialogStyle).show();
        });
    }

    @PermissionCheck(permission = Manifest.permission.WRITE_EXTERNAL_STORAGE)
    public void openAlbum() {
        MatisseManager.start(mActivity, PICTURE_WAY_ALBUM, 1);
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case PICTURE_WAY_TAKE:
                if (resultCode == RESULT_OK) {
                    mCoverPath = tempCoverFile.getPath();
                    GlideManager.loadImage(mActivity, mCoverPath, coverImage);
                    compressCoverFile();
                }
                break;
            case PICTURE_WAY_ALBUM:
                if (resultCode == RESULT_OK) {
                List<Uri> pictureList = MatisseManager.obtainResult(data);
                List<String> picturePathList = PictureUriUtil.handleImageAfterKitKat(getContext(),
                        pictureList);
                mCoverPath = picturePathList.get(0);
                GlideManager.loadImage(mActivity, mCoverPath, coverImage);
                compressCoverFile();
            }
                break;
            case REQUEST_CODE_LOCATION:
                if (resultCode == RESULT_OK) {
                    handleLocationResult(data);
                }
        }
    }

    private void compressCoverFile() {
        if (TextUtils.isEmpty(CACHE_DIR_NAME)) {
            CACHE_DIR_NAME = mActivity.getExternalCacheDir().getAbsolutePath() + File.separator + "BookCache";
            File dirFile = new File(CACHE_DIR_NAME);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
        }
//        LubanUtil.compress(mActivity, mCoverPath, CACHE_DIR_NAME, new OnCompressListener() {
//            @Override
//            public void onStart() {
//
//            }
//
//            @Override
//            public void onSuccess(File file) {
//                mCoverPath = file.getAbsolutePath();
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                Logger.e(TAG, "onError -> 图片压缩失败\n" + e.getMessage());
//            }
//        });
    }

    private void handleLocationResult(Intent data) {
        location = data.getParcelableExtra("result_location");
        if (data == null) {
            return;
        }
        currentLatLon = location.getLatLonPoint();
        currentLocationInfo = location.getCityName() + location.getAdName() + location.getTitle();
        locationBtn.setText("#" + currentLocationInfo + "#");
    }

//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        if (requestCode == PICTURE_ALBUM_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            MatisseManager.start(mActivity, PICTURE_WAY_ALBUM, 1);
//        }
//        if (requestCode == PICTURE_TAKE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            getPicFromCamera();
//        }
//    }

    @PermissionCheck(permission = Manifest.permission.CAMERA)
    public void getPicFromCamera() {
        File tempCoverDir = mActivity.getExternalFilesDir(TEMP_COVER_DIR_NAME);
        if (!tempCoverDir.exists()) {
            tempCoverDir.mkdirs();
        }
        tempCoverFile = new File(tempCoverDir, TEMP_COVER_FILE_NAME + "_"
                + FormatUtil.dateFormatWithLine(System.currentTimeMillis()));
        if (tempCoverFile.exists()) {
            tempCoverFile.delete();
        }
        try {
            tempCoverFile.createNewFile();
            if (Build.VERSION.SDK_INT >= 24) {
                mCoverCameraUri = FileProvider.getUriForFile(mActivity,
                        COVER_FILE_PROVIDER_AUTHORITIES, tempCoverFile);
            } else {
                mCoverCameraUri = Uri.fromFile(tempCoverFile);
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mCoverCameraUri);
            mActivity.startActivityForResult(intent, PICTURE_WAY_TAKE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
